//
//  SearchViewController.swift
//  GiteeClient
//
//  Created by 王志标 on 2020/10/28.
//

import UIKit
import MJRefresh
import PKHUD
import UITableView_FDTemplateLayoutCell
import BTNavigationDropdownMenu

///搜索控制器
class SearchViewController: BaseViewController {

    var searchView:UISearchBar!

    var currentSelectIndexOne = 0
    var currentSelectIndexTwo = 0
    var menu:BTNavigationDropdownMenu!
    var currentLanguage = ""
    var currentSort = ""
    var searchFilterStr = ""
    
    lazy var languageArray:[String] = []
    //排序字段，last_push_at(更新时间)、stars_count(收藏数)、forks_count(Fork 数)、watches_count(关注数)，默认为最佳匹配
    var sortArray = ["", "last_push_at", "stars_count", "forks_count", "watches_count"]
    var sortArrayName = ["最佳排序","更新时间","收藏数","Fork 数","关注数"]
    
    // 列表
    var projectListTableView:UITableView!
    var cellID = "projectitemcellid"
    // 数据源
    lazy var projectArray:ProjectArrayModel = ProjectArrayModel()
    var currentPage = 1
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "搜索"
        self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
        loadLanguages()
        setupTabelview()
        setupSearchbar()
        
    }
    
    //设置排序下拉菜单
    func setupSortMenu(){
        
        menu = BTNavigationDropdownMenu(title: BTTitle.index(0), items: self.sortArrayName)
        
        if #available(iOS 13.0, *) {
            menu.cellBackgroundColor = Colors.backgroundColor
            menu.cellTextLabelColor = Colors.labelColor
        } else {
            menu.cellBackgroundColor = .white
            menu.cellTextLabelColor = .darkGray
        }
        menu.cellSeparatorColor = Colors.BLUE_COLOR
        menu.didSelectItemAtIndexHandler = {[weak self] (indexPath: Int) -> () in
            self?.currentSort = (self?.sortArray[indexPath])!
            self?.loadData(page: 1)
        }
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: menu)
    }
    
    // 设置导航栏下拉菜单
    func setupMenus(){
 
         menu = BTNavigationDropdownMenu(navigationController: self.navigationController, containerView: (self.navigationController?.view)!, title: BTTitle.index(0), items: self.languageArray)
        self.navigationItem.titleView = menu
        
        if #available(iOS 13.0, *) {
            menu.cellBackgroundColor = Colors.backgroundColor
            menu.cellTextLabelColor = Colors.labelColor
        } else {
            menu.cellBackgroundColor = .white
            menu.cellTextLabelColor = .darkGray
        }
        menu.cellSeparatorColor = Colors.BLUE_COLOR
        menu.arrowTintColor = Colors.BLUE_COLOR
        menu.animationDuration = 0.75
        menu.cellHeight = 44
    
        menu.didSelectItemAtIndexHandler = {[weak self] (indexPath: Int) -> () in
            
            self?.currentPage = 1
            self?.currentLanguage = (self?.languageArray[indexPath])!
            self?.loadData(page: self!.currentPage)
        }
    }
    
    // 设置搜索结果表格
    func setupTabelview(){
        
        projectListTableView = UITableView(frame: view.bounds, style: .plain)
        projectListTableView.register(UINib.init(nibName: "ProjectItemTableViewCell", bundle: nil), forCellReuseIdentifier: cellID)
        let value = UIView.AutoresizingMask.flexibleHeight.rawValue | UIView.AutoresizingMask.flexibleWidth.rawValue
        projectListTableView.autoresizingMask = UIView.AutoresizingMask.init(rawValue: value)
        projectListTableView.delegate = self
        projectListTableView.dataSource = self
        projectListTableView.separatorStyle = .none
        view.addSubview(projectListTableView)
        
        let mjH = MJRefreshNormalHeader {
            self.currentPage = 1
            self.loadData(page: self.currentPage)
        }
        mjH?.lastUpdatedTimeLabel.isHidden = true
        projectListTableView.mj_header = mjH
        
        let mjF = MJRefreshBackNormalFooter {
            self.currentPage += 1
            self.loadData(page: self.currentPage)
        }
        projectListTableView.mj_footer = mjF
        
        projectListTableView.emptyDataSetDelegate = self
        projectListTableView.emptyDataSetSource = self
        
        if #available(iOS 13.0, *) {
            projectListTableView.backgroundColor = Colors.backgroundColor
        }
    }
    
    func setupSearchbar(){
        
        searchView = UISearchBar()
        searchView.placeholder = "搜索项目"
        searchView.delegate = self
        
        let vc = UITextField()
        vc.keyboardType = .webSearch
        vc.delegate = self
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        if menu.isShown {
            menu.hide()
        }
    }
}

// MARK: - 搜索框代理方法
extension SearchViewController:UISearchBarDelegate,UITextFieldDelegate {
    
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        self.searchFilterStr = searchText
    }
    
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        self.loadData(page: currentPage)
        searchView.resignFirstResponder()
    }
    
    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        searchView.resignFirstResponder()
    }


}

// MARK: - 加载数据
extension SearchViewController {
    
    // 下拉刷新加载数据
    func loadData(page: Int){
        
        if searchFilterStr.trimmingCharacters(in: .whitespaces).isEmpty {
            self.projectListTableView.mj_header.endRefreshing()
            self.projectListTableView.mj_footer.endRefreshing()
            return
        }
        
        HUD.show(.progress)
        var url = URLs.SEAECHURL
        if !searchFilterStr.isEmpty {
            url += searchFilterStr
        }
        url += "?page=\(page)"
        if !currentLanguage.isEmpty && currentLanguage != "全部语言" {
            url += "&language=" + currentLanguage
        }
        if !currentSort.isEmpty {
            url += "&sort=" + currentSort
        }
        //access_token
//        if let token = UserDefaultTools.getToken() {
//            url += "&access_token=" + token
//        }
        url = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
        print("url = ",url)
        // 异步加载
        DispatchQueue.global().async {
        
            let result:Result<[ProjectMdoel?]> = NetWorkTool.shared.getArrayRequest(url: url, parameters: nil)
            
            DispatchQueue.main.async {
                HUD.hide()
                if result.code == 0 {
                    if page == 1 {
                        self.projectArray.items = result.data as? [ProjectMdoel]
                    }else {
                        self.projectArray.items?.append(contentsOf: (result.data as? [ProjectMdoel])!)
                        if result.data?.count == 0 {
                            self.projectListTableView.mj_footer.endRefreshingWithNoMoreData()
                            return
                        }
                    }
                    self.projectListTableView.reloadData()
                }else {
                    HUD.flash(.label(result.message), delay: 2.0)
                }
                self.projectListTableView.mj_header.endRefreshing()
                self.projectListTableView.mj_footer.endRefreshing()
            }
        }
    }
    
    func loadLanguages(){
        
        let url = URLs.V3URL + URLs.PROJECTS + URLs.LANGUAGE
        self.languageArray.removeAll()
        // 异步加载
        DispatchQueue.global().async {
        
            let result:Result<[LanguageModel?]> = NetWorkTool.shared.getArrayRequest(url: url, parameters: nil)
            DispatchQueue.main.async {
                if result.code == 0 {
                    guard let array = result.data else {
                        return
                    }
                    self.languageArray.append("全部语言")
                    for language in array {
                        self.languageArray.append(language?.name ?? "")
                    }
                    self.setupMenus()
                }else {
                    HUD.flash(.label(result.message), delay: 1.0)
                }
            }
        }
    }
    
    
}

// MARK: - tableview的代理和数据源方法
extension SearchViewController: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return projectArray.items?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! ProjectItemTableViewCell
      
        cell.selectionStyle = .none
        cell.model = projectArray.items![indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return tableView.fd_heightForCell(withIdentifier: cellID) { (cell) in
            
            (cell as! ProjectItemTableViewCell).selectionStyle = .none
            (cell as! ProjectItemTableViewCell).model = self.projectArray.items![indexPath.row]
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let project = projectArray.items![indexPath.row]
        let detialVC = ProjectDetialViewController(project: project)
        detialVC.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(detialVC, animated: true)
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        44
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
      
        return searchView
    }
}
